<script setup>
import {Edit,Delete,Setting} from "@element-plus/icons-vue"
import {computed, getCurrentInstance, onMounted, reactive, ref,} from "vue";
import axios from "axios";
const msg = getCurrentInstance().appContext.config.globalProperties.$message
const confirm=getCurrentInstance().appContext.config.globalProperties.$confirm

//分页组件是否显示
const isPaginationShow=computed(()=>{
  return roleData.value.total > 0;
});

//角色数据表
let roleData=ref({
  roles:[],
  currentPage:1,
  pageSize:10,
  total:0
})

//每页数量改变时
function handlePageSizeChange(){
  selectAllRoles();
}

//当前页改变时
function handleCurrentPageChange(){
  selectAllRoles();
}

//查询所有的角色信息
function selectAllRoles(){
  const options = {
    url: '/role/selectAllRole',
    method: 'GET',
    params: {
      currentPage:roleData.value.currentPage,
      pageSize:roleData.value.pageSize
    },
    headers: {'Content-Type': 'application/json'}
  };

  axios(options).then(res => {
    let rolesData=res.data;
    if (rolesData.meta.code === 200) {
      roleData.value=rolesData.data;
    } else {
      msg.error(rolesData.meta.msg);
    }
  }).catch(err => {
    //网络异常啥的
    msg.error(err);
  })
}

//角色对话框是否显示
let addRoleDialogVisible=ref(false);

//添加角色对话框
function addRoleDialog(){
  addRoleDialogVisible.value=true;
}

let addRoleRef=ref();

//添加角色的数据信息
let addRole=reactive({
  roleName:"",
  roleDesc:""
});

//添加角色校验规则
const addRoleRules=reactive({
  roleName:[
    {
      required:true,
      message: '角色名不能为空!',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 10,
      message: '角色名长度必须在2～10位',
      trigger: 'blur'
    }
  ],
  roleDesc:[
    {
      required:true,
      message: '角色描述不能为空!',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 10,
      message: '角色名长度必须在2～100位',
      trigger: 'blur'
    }
  ]
})

//关闭角色对话框
function handleClosed(){
  addRoleRef.value.resetFields();
  addRoleDialogVisible.value=false;
}
//关闭角色对话框
function closeDialog(){
  handleClosed();
}

//添加角色
function submitAddRoleForm(addRoleRef){
  addRoleRef.validate(async validate =>{
    if (!validate) return
    //更改密码的数据
    const options = {
      url: '/role/addRole',
      method: 'post',
      data: {
        roleName:addRole.roleName,
        roleDesc:addRole.roleDesc
      },
      headers: {'Content-Type': 'application/json'}
    };

    axios(options).then(res => {
      let mg = res.data;
      if (mg.meta.code === 200) {
        selectAllRoles();
        //添加角色成功！
        msg.success(mg.meta.msg);
        //关闭添加角色对话框
        closeDialog();
      } else {
        msg.error(mg.meta.msg);
      }
    }).catch(err => {
      //网络异常啥的
      msg.error(err);
    })
  });
}

let editRoleDialogVisible=ref(false);

let editRoleRef=ref();

//角色编辑数据
let editRole=ref({
  id:"",
  roleName:"",
  roleDesc:""
});

const editRoleRules=reactive({
  roleName:[
    {
      required:true,
      message: '角色名不能为空!',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 10,
      message: '角色名长度必须在2～10位',
      trigger: 'blur'
    }
  ],
  roleDesc:[
    {
      required:true,
      message: '角色描述不能为空!',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 10,
      message: '角色描述长度必须在2～100位',
      trigger: 'blur'
    }
  ]
})

//关闭角色编辑对话框
function handleEditRoleClosed(){
  editRoleRef.value.resetFields();
  editRoleDialogVisible.value=false;
}

//关闭角色编辑对话框
function closeEditRoleDialog(){
  handleEditRoleClosed();
}

//编辑角色对话框
function editRoleDialog(id){
  //查询角色信息
  const options = {
    url: '/role/selectSingleRole',
    method: 'GET',
    params: {
      id:parseInt(id)
    },
    headers: {'Content-Type': 'application/json'}
  };

  axios(options).then(res => {
    let rolesData=res.data;
    if (rolesData.meta.code === 200) {
      editRole.value=rolesData.data;
      editRoleDialogVisible.value=true;
    } else {
      msg.error(rolesData.meta.msg);
    }
  }).catch(err => {
    //网络异常啥的
    msg.error(err);
  })
}

//提交编辑数据
function submitEditRoleForm(editRoleRef){
  editRoleRef.validate(async validate =>{
    if (!validate) return
    //更改密码的数据
    const options = {
      url: '/role/updateRole',
      method: 'put',
      data: {
        id:parseInt(editRole.value.id),
        roleName:editRole.value.roleName,
        roleDesc:editRole.value.roleDesc
      },
      headers: {'Content-Type': 'application/json'}
    };

    axios(options).then(res => {
      let mg = res.data;
      if (mg.meta.code === 200) {
        let roles=roleData.value.roles
        roles.forEach((role,index)=>{
          if(role.id===mg.data.id){
            roles[index]=mg.data;
          }
        })
        //更新角色成功！
        msg.success(mg.meta.msg);
        //关闭编辑角色对话框
        closeEditRoleDialog();
      } else {
        msg.error(mg.meta.msg);
      }
    }).catch(err => {
      //网络异常啥的
      msg.error(err);
    })
  });
}

//删除角色
async function deleteRoleDialog(id){
  // 弹框询问用户是否删除
  const confirmResult = await confirm('此操作将永久删除该角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).catch(err => err)
  // 如果用户确认删除，则返回字符串confirm
  // 如果用户取消了删除，则返回字符串cancel
  if (confirmResult !== 'confirm') {
    return msg.info('角色取消删除！');
  }

  axios.delete("/role/deleteRole/"+id).then(res => {
    let mg = res.data;
    if (mg.meta.code === 200) {
      let tempIndex=0;
      let roles=roleData.value.roles
      roles.forEach((role,index)=>{
        if(role.id===id){
          tempIndex=index;
        }
      })
      roles.splice(tempIndex,1);
      roleData.value.total=roleData.value.total-1;
    }
  }).catch(err =>{
    msg.error(err);
  })
}

const defaultProps={
  children:'children',
  label:'authorName'
}

//默认选中的节点
let defaultCheckedKeys=[];

//树形权限数据列表
const data=ref([]);

//角色授权对话框是否打开
let roleAuthorDialogVisible=ref(false);

//查询所有的权限树形数据结构
function selectAllAuthor(){
  const options = {
    url: '/permission/selectAllPermission',
    method: 'get',
    headers: {'Content-Type': 'application/json'}
  };

  axios(options).then(res => {
    let mg = res.data;
    if (mg.meta.code === 200) {
      data.value=mg.data;
    } else {
      msg.error(mg.meta.msg);
    }
  }).catch(err => {
    //网络异常啥的
    msg.error(err);
  })
}

let roleId=ref();

//查询角色所具有的权限
function selectRoleAuthor(id){
  roleId.value=id;
  const options = {
    url: '/permission/selectRoleAuthor',
    method: 'get',
    params:{
      id:parseInt(id)
    },
    headers: {'Content-Type': 'application/json'}
  };

  axios(options).then(res => {
    let mg = res.data;
    if (mg.meta.code === 200) {
      //返回这个角色所具有的权限数组，使用平常的数组存储
      defaultCheckedKeys=mg.data;
      //roleAuthor=mg.data;
    } else {
      msg.error(mg.meta.msg);
    }
  }).catch(err => {
    //网络异常啥的
    msg.error(err);
  })
}

//角色赋权对话框
function updateRoleDialog(id){
  //查询所有的权限，树形权限列表
  selectAllAuthor();
  //根据角色id查询该角色所具有的权限并存储在  默认选中的节点 'defaultCheckedKeys'
  selectRoleAuthor(id);
  setTimeout(()=>{
    roleAuthorDialogVisible.value=true;
  },50);
}

//关闭角色授权对话框
function handleRoleAuthorClosed(){
  defaultCheckedKeys=[];
  roleAuthorDialogVisible.value=false;
}

//关闭角色授权对话框
function closeRoleAuthorDialog(){
  handleRoleAuthorClosed();
}

let treeRef=ref();

//提交数据
function submitRoleAuthorForm(){
  let checkedArr=treeRef.value.getCheckedKeys();
  let halfCheckedArr=treeRef.value.getHalfCheckedKeys();
  let newPsIdArr=[...checkedArr,...halfCheckedArr];
  //roleId
  const options = {
    url: '/role/roleAuthorize',
    method: 'post',
    data:{
      id: roleId.value,
      psIds: newPsIdArr
    },
    headers: {'Content-Type': 'application/json'}
  };

  axios(options).then(res => {
    let mg = res.data;
    if (mg.meta.code === 200) {
      handleRoleAuthorClosed();
      msg.success(mg.meta.msg);
    } else {
      msg.error(mg.meta.msg);
    }
  }).catch(err => {
    //网络异常啥的
    msg.error(err);
  })


}


//挂载完毕之后
onMounted(()=>{
  selectAllRoles();
})

</script>

<template>
  <el-card>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path:'/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-row :gutter="20">
      <el-col :span='21'></el-col>
      <el-col :span='3'>
        <el-button type="primary" @click='addRoleDialog'>添加角色</el-button>
      </el-col>
    </el-row>
    <!--表格数据-->
    <el-table :data="roleData.roles" border style="width: 100%" stripe>
      <el-table-column label="序列" width="60" type="index"></el-table-column>
      <el-table-column prop="roleName" label="角色名" width="120"/>
      <el-table-column prop="roleDesc" label="角色描述" width="720"/>
      <el-table-column label="操作">
        <template v-slot:="scope">
          <el-button type="primary" :icon="Edit" size='small'  @click="editRoleDialog(scope.row.id)">编辑</el-button>
          <el-button type="danger"  :icon="Delete" size='small'  @click="deleteRoleDialog(scope.row.id)">删除</el-button>
          <el-button type="warning" :icon="Setting" size='small'  @click="updateRoleDialog(scope.row.id)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <el-pagination
        v-show="isPaginationShow"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        background
        layout="prev,pager,next,total,sizes,jumper"
        v-model:current-page="roleData.currentPage"
        v-model:page-size="roleData.pageSize"
        :page-sizes="[10,15,20,25]"
        :total="roleData.total">
    </el-pagination>

    <!--添加角色-->
    <el-dialog v-model="addRoleDialogVisible"
               title="添加角色"
               width="32%"
               :before-close="handleClosed">
      <el-form :rules="addRoleRules" :model="addRole" ref="addRoleRef" status-icon>
        <!--角色名-->
        <el-form-item prop="roleName" label="角色名" label-width="80">
          <el-input v-model="addRole.roleName"
                    class="w-50 m-2"
                    placeholder="请输入用户名"
                    size="large"
                    autocomplete="off"
                    clearable validate-event>
          </el-input>
        </el-form-item>

        <!--角色描述-->
        <el-form-item prop="roleDesc" label="角色描述" label-width="80">
          <el-input v-model="addRole.roleDesc"
                    type="textarea"
                    placeholder="请输入用户名"
                    size="large"
                    autocomplete="off"
                    clearable validate-event>
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitAddRoleForm(addRoleRef)">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!--编辑角色-->
    <el-dialog v-model="editRoleDialogVisible"
               title="编辑角色"
               width="32%"
               :before-close="handleEditRoleClosed">
      <el-form :rules="editRoleRules" :model="editRole" ref="editRoleRef" status-icon>
        <!--角色名-->
        <el-form-item prop="roleName" label="角色名" label-width="80">
          <el-input v-model="editRole.roleName"
                    class="w-50 m-2"
                    placeholder="请输入用户名"
                    size="large"
                    autocomplete="off"
                    clearable validate-event>
          </el-input>
        </el-form-item>

        <!--角色描述-->
        <el-form-item prop="roleDesc" label="角色描述" label-width="80">
          <el-input v-model="editRole.roleDesc"
                    type="textarea"
                    placeholder="请输入用户名"
                    size="large"
                    autocomplete="off"
                    clearable validate-event>
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeEditRoleDialog">取消</el-button>
          <el-button type="primary" @click="submitEditRoleForm(editRoleRef)">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!--角色赋权-->
    <el-dialog v-model="roleAuthorDialogVisible"
               title="角色赋权"
               width="30%"
               :before-close="handleRoleAuthorClosed">

      <el-tree
        :data="data"
        ref="treeRef"
        show-checkbox
        node-key="id"
        empty-text="没有任何权限"
        default-expand-all
        highlight-current
        :default-checked-keys="defaultCheckedKeys"
        :props="defaultProps">

      </el-tree>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeRoleAuthorDialog">取消</el-button>
          <el-button type="primary" @click="submitRoleAuthorForm()">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<style scoped>
.el-row{
  margin-bottom: 20px;
}

.el-pagination{
  margin-top: 10px;
  justify-content: center;
}
</style>
